package com.lqfan.autoAnswerQ.controller.subject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lqfan.autoAnswerQ.model.errorRecords.ImportErrorRecords;
import com.lqfan.autoAnswerQ.model.quesBank.QuesBankModel;
import com.lqfan.autoAnswerQ.model.quesBank.Question;
import com.lqfan.autoAnswerQ.model.subject.HandleImportModel;
import com.lqfan.autoAnswerQ.model.subject.Subject;
import com.lqfan.autoAnswerQ.model.subjectChoiceType.SubjectChoiceType;
import com.lqfan.autoAnswerQ.service.errorRecords.IImportErrorRecordsService;
import com.lqfan.autoAnswerQ.service.quesBank.IQuestionService;
import com.lqfan.autoAnswerQ.service.subject.ISubjectService;
import com.lqfan.autoAnswerQ.service.subject.impl.SubjectServiceImpl;
import com.lqfan.autoAnswerQ.service.subjectChoiceType.ISubjectChoiceTypeService;
import com.lqfan.autoAnswerQ.utils.ResponseMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  题目  控制器
 * </p>
 *
 * @author lqfan
 * @since 2020-04-09
 */

@RestController
@RequestMapping(value = "/api",produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "题目相关接口")
public class SubjectController {
    private static final Logger logger = LoggerFactory.getLogger(SubjectController.class);

    @Autowired
    private ISubjectService subjectService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ISubjectChoiceTypeService subjectChoiceTypeService;
    @Autowired
    private IImportErrorRecordsService errorRecordsService;

    @ApiOperation(value = "获取题目相关信息", notes = "获取题目相关信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "quesBankId", value = "题库id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "每页的显示数量", required = true, dataType = "int")
    })
    @RequestMapping(value = "getSubjectWithPage", method = RequestMethod.POST)
    public ResponseMessage getSubjectWithPage(@RequestParam(value = "userId") String userId,
                                              @RequestParam(value = "quesBankId") String quesBankId,
                                              @RequestParam(value = "currentPage") int currentPage,
                                              @RequestParam(value = "limit") int limit) {
        logger.info("获取题目信息");
        QuesBankModel quesBankModel = new QuesBankModel();
        //获取题库
        questionService.updateDoNum(userId,quesBankId);
        Question question = questionService.getById(quesBankId);
        quesBankModel.setFileName(question.getQuestionName());
        quesBankModel.setFilePath(question.getFilePath());
        quesBankModel.setQuestionFileType(question.getQuestionFileType());
        quesBankModel.setUserId(question.getUserId());
        QuesBankModel res = subjectService.getSubjectWithPage(quesBankModel, userId, quesBankId, currentPage, limit);
        return ResponseMessage.success(res);
    }

    @ApiOperation(value = "共享性的，获取单个题目", notes = "获取单个题目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "subjectId", value = "题目id", required = true, dataType = "String"),
    })
    @RequestMapping(value = "getOneSubject", method = RequestMethod.POST)
    public ResponseMessage getOneSubject(@RequestParam(value = "userId") String userId,
                                              @RequestParam(value = "subjectId") String subjectId) {
        logger.info("共享性的，获取单个题目");
        QuesBankModel quesBankModel = new QuesBankModel();
        //获取题库
        quesBankModel.setFileName("题目");
        quesBankModel.setFilePath("xxx");
        quesBankModel.setQuestionFileType(0);
        quesBankModel.setUserId(userId);
        QuesBankModel res = subjectService.getOneSubject(quesBankModel, userId, subjectId);
        return ResponseMessage.success(res);
    }

    @ApiOperation(value = "删除题目或选项", notes = "删除题目或选项")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subjetcId", value = "题目id", dataType = "String"),
            @ApiImplicitParam(name = "choiceId", value = "选项id", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String")
    })
    @RequestMapping(value = "delSubject", method = RequestMethod.POST)
    public ResponseMessage delSubject(@RequestParam(value = "subjetcId", required = false) String subjetcId,
                                      @RequestParam(value = "choiceId", required = false) String choiceId,
                                      @RequestParam(value = "userId", required = true) String userId) {
        logger.info("删除对应的题目和选项");
        try {
            if (!subjetcId.isEmpty()) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("id", subjetcId);
                boolean resS = subjectService.remove(queryWrapper);
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("subjectId", subjetcId);
                boolean resC = subjectChoiceTypeService.remove(queryWrapper1);
                if (resS && resC) {
                    return ResponseMessage.success("删除成功");
                }
            } else if (!choiceId.isEmpty()) {
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("id", choiceId);
                boolean resC = subjectChoiceTypeService.remove(queryWrapper1);
                if (resC) {
                    return ResponseMessage.success("删除成功");
                }
            } else {
                return ResponseMessage.fail("参数错误");
            }
        } catch (Exception e) {
            logger.info("删除失败");
            ImportErrorRecords errorInfo = new ImportErrorRecords();
            errorInfo.setErrorContent("删除题目/选项失败");
            errorInfo.setUserId(userId);
            errorRecordsService.saveErrInfo(errorInfo);
            return ResponseMessage.fail("删除失败");
        }

        return ResponseMessage.success("删除成功");
    }

    @ApiOperation(value = "获取对应用户收藏的题目", notes = "获取对应用户收藏的题目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
    })
    @RequestMapping(value = "getCollectSubject", method = RequestMethod.POST)
    public ResponseMessage getCollectSubject(@RequestParam(value = "userId") String userId) {
        logger.info("获取对应用户收藏的题目");
        List<Subject> s = subjectService.getCollectSubject(userId);
        if (s==null){
            return ResponseMessage.fail("暂无收藏信息");
        }
        return ResponseMessage.success(s);
    }

    @ApiOperation(value = "新增/修改 题目或选项", notes = "新增/修改 题目或选项")
    @ApiImplicitParam(name = "quesBankModel", value = "题目对象", required = true, dataType = "json")
    @RequestMapping(value = "handleSubject", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseMessage handleSubject(@RequestBody QuesBankModel quesBankModel) {
        String questionId = quesBankModel.getQid();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("questionId", questionId);

        ArrayList<HandleImportModel> handleImportModels = quesBankModel.getHandleImportModels();
        ArrayList<Subject> subjectArrayList = new ArrayList<>();
        for (HandleImportModel model : handleImportModels) {
            Subject subject = new Subject();
            subject.setAnswer(model.getAnswer());
            subject.setTypeId(model.getTypeId());
            subject.setContent(model.getContent());
            if (model.getId()==null) {
                subject.setId(String.valueOf(UUID.randomUUID()));
            } else {
                subject.setId(model.getId());
            }
            subject.setIsCollect(model.getIsCollect());
            subject.setQuestionId(model.getQuestionId());
            subjectArrayList.add(subject);

            ArrayList<SubjectChoiceType> choiceList = model.getChoiceList();
            for (SubjectChoiceType choice : choiceList) {
                choice.setSubjectId(subject.getId());
            }
            boolean resC = subjectChoiceTypeService.saveOrUpdateBatch(choiceList);
            if (!resC) {
                logger.error("新增/修改 选项失败");
                ImportErrorRecords errorInfo = new ImportErrorRecords();
                errorInfo.setErrorContent("新增/修改 选项失败");
                errorInfo.setUserId(quesBankModel.getUserId());
                errorRecordsService.saveErrInfo(errorInfo);
                return ResponseMessage.fail("新增/修改 选项失败");
            }

        }
        boolean res = subjectService.saveOrUpdateBatch(subjectArrayList);
        if (!res) {
            logger.error("新增/修改 题目失败");
            ImportErrorRecords errorInfo = new ImportErrorRecords();
            errorInfo.setErrorContent("新增/修改 选项失败");
            errorInfo.setUserId(quesBankModel.getUserId());
            errorRecordsService.saveErrInfo(errorInfo);
            return ResponseMessage.fail();
        }
        return ResponseMessage.success("新增/修改 题目成功");
    }

    @ApiOperation(value = "收藏题目", notes = "收藏题目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isCollect", value = "是否收藏0为不收藏，1为收藏", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "id", value = "题目id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
    })
    @RequestMapping(value = "collect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseMessage handleSubject(@RequestParam("isCollect") Integer isCollect,
                                         @RequestParam("id") String id,
                                         @RequestParam("userId") String userId) {
        int result = subjectService.collectSub(isCollect, id, userId);
        switch (result) {
            case 0:
                return ResponseMessage.fail("收藏失败");
            case 1:
                if (isCollect==0){
                    return ResponseMessage.success("取消收藏成功");
                }else {
                    return ResponseMessage.success("收藏成功");
                }

            default:
                return ResponseMessage.fail("收藏失败");
        }

    }
}
